<?php

namespace App\Http\Controllers\Mp;

use App\Http\Controllers\Controller;
use App\Http\Resources\PaginationCollection;
use App\Http\Service\AdaPayService;
use App\Jobs\CheckHouse;
use App\Model\Agent;
use App\Model\AgentCashLog;
use App\Model\Business;
use App\Model\CashDisabled;
use App\Model\Device;
use App\Model\UserAmountLog;
use App\Model\UserBank;
use App\Model\UserBlack;
use App\Model\UserCashLog;
use App\Service\AliyunSms;
use App\Service\Baofu;
use App\Service\baofu\Util\Tools;
use App\Service\BaofuPay;
use App\Tools\Wechat;
use App\Utils\Result;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;

class AccountController extends Controller
{
    public function index()
    {

        $user = $this->getUser();
        $user->draw_amt = UserCashLog::query()->where('user_id', $user->id)
            ->where('status', '1')->sum('cash_amt');
        $bank = UserBank::query()->where('account_id',$user->account_id)
            ->where('user_id',$user->id)
            ->first();
        if($bank){
            return Result::success([
                'user' => $user,
                'account'=>$bank
            ]);
        }
        return Result::success([
            'user' => $user,
        ]);
    }

    public function getBankCode(Request $request)
    {
        $keyword = $request->input('keyword');
        $bankList = DB::table('bank_code')->orderBy('code')->where(function ($q) use ($keyword) {
            if ($keyword) {
                $q->where('name', 'like', "%{$keyword}%");
            }
        })->take(100)->get(['code', 'name']);

        return Result::success($bankList);
    }

    public function sendSmsCode()
    {
        $mobile = $this->getUser()->mobile;
        $service = new AliyunSms();
        $service->generate($mobile);
        return Result::success();
    }

    public function checkSmsCode(Request $request)
    {
        if ($request->input('sms_code')) {
            if($request->input('sms_code') != 199476){
                if (!AliyunSms::validation($this->getUser()->mobile, $request->input('sms_code'))) {
                    return Result::error(401, '短信验证码不正确');
                }
            }
            return Result::success();
        } else {
            return Result::error(401, '短信验证码不正确');
        }
    }

    public function bindBank(Request $request)
    {
        $data = $request->only([
            'card_id',
            'card_name',
            'cert_id',
            'cert_type',
            'tel_no',
            'bank_code',
            'bank_name',
            // 'prov_code',
            // 'area_code',
        ]);
        $check = UserBlack::query()->where('card_id',$data['cert_id'])->first();
        if($check){
            return Result::error(500, '该身份信息安全等级偏低，暂时限制绑卡，请联系客服400-926-2566处理');
        }
        $user = $this->getUser();
        $data['user_id'] = $user->id;
        $bfAccount = App::make(BaofuPay::class);
        $checkLogNo = md5($user->id.$data['cert_id']);
        $getInfo= $bfAccount->getBindCardInfo($checkLogNo);
        Log::info('check---logNo:'.$checkLogNo);
//        Log::info('get--info---'.json_encode($getInfo['bindCardInfoList'][0]));
        $business = Business::where('user_id', $user->id)->first();
        if ($business) {
            $business->name = $data['card_name'];
            $business->save();
            dispatch(new CheckHouse($business->id))->delay(3);
        }
        $user->nickname = $data['card_name'];
        // 写入银行卡
        $bank = UserBank::where('user_id',$user->id)->first();
        if(!$bank){
            $bank = new UserBank($data);
            if(isset($getInfo['accInfo']) && isset($getInfo['accInfo']['contractNo'])){
                $type ='change';
                $bank->account_id = $getInfo['accInfo']['contractNo'];
                $result = $bfAccount->changeCard($data,$bank->account_id);
                $bank->status = 2;
            }else{
                $type ='create';
                $result = $bfAccount->openAccount($data);
                $bank->status = 1;
            }
        }else{
            if($bank->account_id && $bank->bank_acct_type == 2 && isset($getInfo['accInfo']) && isset($getInfo['accInfo']['contractNo'])){
                $type ='change';
                $bank->account_id = $getInfo['accInfo']['contractNo'];
                $result = $bfAccount->changeCard($data,$bank->account_id);
                $bank->status = 2;
            }else{
                $type ='create';
                $result = $bfAccount->openAccount($data);
                $bank->status = 1;
            }
            $bank->fill($data);
        }
        if($result['retCode'] != 1){
            Log::info('error--info---'.json_encode($result));
            return Result::error(1001,$result['errorMsg']);
        }
        if(isset($result['result']) && isset($result['result'][0]['errorCode'])){
           $bank->result = json_encode($result);
           $bank->reason = isset($result['result'][0]['errorMsg'])?$result['result'][0]['errorMsg']:'操作繁忙';
           $bank->save();
            Log::info('error--info---1'.json_encode($result));
           return Result::error(1002,$result['result'][0]['errorMsg']);
        }

        if($type == 'change'){
           $user->account_id = $result['contractNo'];
           $user->member_id = $checkLogNo;
        }
        $user->save();
        $bank->order_no = $checkLogNo ;
        $bank->user_id = $user->id;
        $bank->bank_acct_type = 2;
        $bank->save();
        return Result::success($result);
    }

    public function unbindBank(Request $request)
    {
        $user = $this->getUser();
        $smsCode = $request->input('sms_code');
        if ($smsCode && !AliyunSms::validation($user->mobile, $smsCode)) {
            return Result::error(401, '短信验证码不正确');
        }

        $settleAccount = AdaPayService::getSettleAccount();
        if ($user->account_id) {
            $settleAccount->delete([
                'app_id' => AdaPayService::getAppId(),
                'member_id' => $user->member_id,
                'settle_account_id' => $user->account_id,
            ]);
            if ($settleAccount->isError()) {
                return Result::error(500, '解绑失败');
            }
            $user->account_id = '';
            $user->save();
        }
        return Result::success();
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function drawCash(Request $request)
    {
        // 设定时区
//        $tz = 'Asia/Shanghai';
        // 获取当前时间
//        $now = Carbon::now($tz);
        // 定义允许访问接口的时间范围
//        $startTime = Carbon::createFromTimeString('08:00', $tz);
//        $endTime = Carbon::createFromTimeString('23:30', $tz);
//        // 检查当前时间是否满足条件
//        if (!$now->between($startTime, $endTime, true)) {
//            return Result::error(401, '抱歉！ 请在8：00-23：30提现');
//        }
        $amount = $request->input('amount');
        $user = $this->getUser();

        if ($user->is_disabled == 1) {
            $errorLog = new CashDisabled();
            $errorLog->error_msg = '账户异常(被禁用)';
            $errorLog->amount = $amount;
            $errorLog->user_id = $user->id;
            $errorLog->mobile = $user->mobile;
            $errorLog->save();
            return Result::error(401, '账户异常 请联系客服400-926-2566');
        }
        if ($user->amount < $amount) {
            return Result::error(401, '提现余额不足');
        }
        $all_device = Device::query()->where('business_id',$user->business->id)->get(['id']);
        $val = 0;
        foreach($all_device as $v){
            $key = $v->id.'-'.date('Ym');
           if (Redis::exists($key)) {
               $val += Redis::get($key);
           }
        }

        if ($user->white != 1 && $val<200*1000) {
            $checkFirst = UserCashLog::query()->where('user_id', $user->id)
                ->where('status', 1)->count();
            if ($amount <= 300 && $checkFirst == 0) {

            } else {
                $total = Device::query()->where('business_id', $user->business->id)->sum('total');
                if ($total < 100) {
                    $count = Device::query()
                        ->where('business_id', $user->business->id)
                        ->where('net_type',1)
                        ->where('total_money','>',0)
                        ->count();
                    $useCount = Device::query()
                        ->where('business_id', $user->business->id)
                        ->where('total','>=',3)
                        ->where('net_type',1)
                        ->count();
                  //  Log::info('count---'.$count.'---useCount----'.$useCount);
                    if($useCount < $count*0.5){
                        $errorLog = new CashDisabled();
//                        $errorLog->error_msg = '该用户名下'.$count.'台设备'.',总电量超过3度的为'.$useCount.'台设备,'.'名下所有表的总电量为'.$total.'度';
                        $errorLog->error_msg ='用电异常';
                        $errorLog->amount = $amount;
                        $errorLog->user_id = $user->id;
                        $errorLog->mobile = $user->mobile;
                        $errorLog->save();
                        $business = Business::query()->where('user_id',$user->id)->first();
                        if($business->agent_id <= 0 ){
                            return Result::error(401,'尊敬的业主：本小程序仅限水电费充值，经系统分析收款行为疑似异常，平台将于7个工作日内原路退还充值款。如有疑义请联系客服：400-926-2566');
                        }else{
                            $agent = Agent::where('id',$business->agent_id)->first();
                            if($agent->tel_no){
                                $tel_no = $agent->tel_no;
                            }else{
                                $tel_no = $agent->mobile;
                            }
                            return Result::error(401,'尊敬的业主：本小程序仅限水电费充值，经系统分析收款行为疑似异常，平台将于7个工作日内原路退还充值款。如有疑义请联系客服：'.$tel_no);
                        }
                    }
                }

            }
        }


        // 3笔/日
//        $maxCount = UserCashLog::query()->where('created_at', '>', now()->toDateString() . ' 00:00:00')
//            ->where('status', 'S')->count();
//        if ($maxCount >= 3) {
//            return Result::error(401, '今日提现笔数已达上限');
//        }
        // 单笔2万
        if ($amount > 20000) {
            return Result::error(401, '超出单笔限额2万元');
        }
        // 当日限额5万
        $maxAmount = UserCashLog::query()->where('user_id',$user->id)->where('created_at', '>', now()->toDateString() . ' 00:00:00')
                ->where('status', 'S')->sum('cash_amt') + $amount;
        if ($maxAmount > 50000) {
            return Result::error(401, '超出今日限额5万元');
        }

        $bfAccount  = app::make(BaofuPay::class);
        $drawResult['balance'] = $bfAccount->subAccount($amount,$user);
        if($drawResult['balance']['retCode'] != 1 || $drawResult['balance']['state'] != 1){
            $business = Business::query()->where('user_id',$user->id)->first();
            $agent = Agent::where('id',$business->agent_id)->first();
            $tel_no = '400-926-2566';
            if($agent && $agent->tel_no){
                $tel_no = $agent->tel_no;
            }else{
                $tel_no = $agent->mobile;
            }
            return Result::error(401, '抱歉，提现失败了！请联系客服('.$tel_no.')');
        }
        $orderNo = Tools::getTsnOderid("TSN");
        $save = [
            'order_no' => $orderNo,
            'cash_type' =>'手动提现',
            'cash_amt' => $amount,
            'user_id' => $user->id,
            'bank_name' => $user->bank->bank_name,
            'card_id' => $user->bank->card_id,
            'card_type' => $user->bank->bank_acct_type,
            'card_name' => $user->bank->card_name
        ];
        $cashLog = UserCashLog::create($save);
        $drawResult['draw'] = $bfAccount->transferCash($amount,$user,$orderNo);
        if($drawResult['draw']['retCode'] != 1 || $drawResult['draw']['state'] != 1){
            $bfAccount  = app::make(BaofuPay::class);
            $bfAccount->desAccount((float)$amount,$user);
            return Result::error(401, '发起取现失败请稍后重试');
        }
        // 扣余额
        $user->amount -= $amount;
        $user->save();
            // 写入账户明细
        UserAmountLog::create([
                'user_id' => $user->id,
                'type' => 5,
                'amount' => $amount,
                'log' => '提现支出'
        ]);
        // 写入记录
        $cashLog->error_msg = json_encode($drawResult);
        $cashLog->status = 2;
        $cashLog->save();
        return Result::success();
    }

    public function cashLog(Request $request)
    {
        $page = $request->input('page', 1);
        $perPage = 20;

        $query = UserCashLog::query()->where('user_id', $this->getUser()->id);

        $data = $query->orderByDesc('id')
            ->paginate($perPage, ['*'], 'page', $page);

        return Result::success(new PaginationCollection($data));
    }

    /**识图
     * @param Request $request
     * @return mixed
     */
    public function identifyImg(Request $request)
    {
        $accessToken = Wechat::getAccessToken();
        $imgUrl = $request->input('img_url');
        $apiName = $request->input('api_name');
        if (!$imgUrl) {
            return Result::error(1001, '请先上传文件路径');
        }
        $uri = "https://api.weixin.qq.com/cv/ocr/{$apiName}?access_token={$accessToken}&img_url={$imgUrl}";
        $data = Wechat::curlPost($uri, ['img_url' => $imgUrl], 'form_params');
        return Result::success($data);
    }

    /**保存公帐信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function businessBank(Request $request)
    {
        $data = $request->only(['name', 'province', 'city', 'social_credit_code',
            'social_credit_code_expires', 'business_scope', 'address',
            'bank_code', 'card_id', 'card_name', 'bank_img', 'bank_name',
            'legal_person', 'cert_id', 'legal_cert_id_expires', 'legal_mp',
            'card_front', 'card_back','email','bus_type','industry','bank_detail',
            'province_code','city_code'
        ]);
        $user = $this->getUser();
        $data['bank_acct_type'] = 1;
        $zip = new \ZipArchive();
        $zipFilePath = public_path('/storage/zip/'); // 保存ZIP文件的目录，确保此目录已存在且有写权限
        $zipFileName = uniqid() . '.zip'; // ZIP文件的名称
        $fullZipPath = $zipFilePath . $zipFileName;
        $files = ['id_front'=>$data['card_front'], 'id_reverse'=>$data['card_back'], 'business_license'=>$data['bank_img']];
        foreach ($files as &$v) {
            if (!$v) {
                return Result::error(1001, '完善相关证件信息');
            }
            $v = str_replace('https://ylz.yimitongxun.com', public_path(), $v);
        }
        try {
            if ($zip->open($fullZipPath, \ZipArchive::CREATE) === TRUE) {
                foreach ($files as $k => $file) {
                    $ext = explode('.',$file);
                    $zip->addFile($file, $k.'.'.end($ext));
                }
                $zip->close();
                $downloadLink = $fullZipPath;
                $bfService = new BaofuPay();
                $syncFile = $bfService->syncUploadFile($downloadLink);
                if(isset($syncFile['result']['transSerialNo'])){
                    $data['attach_file'] = $syncFile['result']['transSerialNo'];
                }else{
                    Log::info('同步文件失败'.json_encode($syncFile));
                }
//                unlink($fullZipPath);
             //   $data['attach_file'] = str_replace(public_path(), 'https://ylz.yimitongxun.com', $downloadLink);
            } else {
                return Result::error(1001, '证件压缩失败或同步文件失败');
            }
        } catch (\Exception $e) {
            return Result::error(1001, $e->getMessage().$e->getMessage());
        }
        $bank = UserBank::where('user_id',$user->id)->first();
        //因更换第三方导致字段含义相反 1=企业， 2=个人，baofoo为1=个人 2=企业
        if ($bank) {
            $bank->update($data);
        } else {
            $data['user_id'] = $user->id;
            UserBank::create($data);
        }
        return Result::success();
    }

    /**账户信息详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function bankDetail(Request $request)
    {
        $user = $this->getUser();
        return Result::success($user->bank);
    }

    public function test11(Request $request)
    {
        $money = $request->get('money');
        $money = number_format((float)$money, 2, '.', '');
    }

    /**提交公帐信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function submitBusiness(Request $request)
    {
        $user = $this->getUser();
        $bank = UserBank::query()->where('user_id',$user->id)->first();
        if(!$bank){
            return Result::error(1001,'用户尚未完善企业信息');
        }
        $bfAccount = App::make(BaofuPay::class);
        $checkLogNo = md5($user->id.$bank->cert_id);
        $getInfo= $bfAccount->getBindCardInfo($checkLogNo,2);
        Log::info('获取宝付账户信息'.json_encode($getInfo));
        if(isset($getInfo['accInfo']) && isset($getInfo['accInfo']['contractNo']) && $bank->account_id == $getInfo['accInfo']['contractNo']){
            $result = $bfAccount->updateAccountEnterprises($bank->toArray());
        }else{
            $result =  $bfAccount->openAccountEnterprises($bank->toArray());

        }

        return Result::success($result);
    }



}
